package com.example.chartgpt.controller;

import com.example.chartgpt.service.IJson;
import com.example.chartgpt.service.JsonServiceImp;
import com.example.chartgpt.service.OpenAiService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
public class OpenAiController {

    @Autowired
    private OpenAiService openAIService;
    @Autowired
    private JsonServiceImp jsonServiceImp;

    @GetMapping("/chat_input")
    public ModelAndView input() {
        ModelAndView modelAndView = new ModelAndView("input");
        return modelAndView;
    }

    @PostMapping("/chat")
    public ResponseEntity<String> callOpenAI(@RequestBody String requestBody) {
        try {
            System.out.println(requestBody);
            String response = openAIService.OpenAiQuestion(requestBody);
            String answer = jsonServiceImp.JsontoString(response);
            return ResponseEntity.ok(answer);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred: " + e.getMessage());
        }
    }
}
